import React, { useState, useRef, useEffect } from 'react';
import axios from 'axios';
import 'nprogress/nprogress.css';
import NProgress from 'nprogress';
import message from '@/components/common/message';
import Image from 'next/image';
import { ImageUp, Plus } from 'lucide-react';
import Popup from '@/components/admin/common/Popup';
import Pagination from '@/components/client/common/Pagination';

export default function ImageUpload({ label, value, handleChange, state, className }) {
  const [imageUrl, setImageUrl] = useState(value || '');
  const [showImageList, setShowImageList] = useState(false);
  const [uploadedImages, setUploadedImages] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(1);
  const [limit] = useState(16);
  const inputRef = useRef(null);

  useEffect(() => {
    setImageUrl(value || '');
  }, [value]);

  const handleImageChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setImageUrl(reader.result);
        const formData = new FormData();
        formData.append('file', file);
        NProgress.start();
        axios.post('/api/admin/files', formData, {
          onUploadProgress: (event) => {
            if (event.total) {
              const percent = Math.round((event.loaded / event.total) * 100);
              NProgress.set(percent / 100);
            }
          }
        }).then(res => {
          if (res.data.url) {
            message.success('上传成功！');
            handleChange(res.data.url);
          }
          NProgress.done();
        }).catch(() => {
          message.error('上传失败');
          NProgress.done();
        });
      };
      reader.readAsDataURL(file);
    }
  };

  const handleImageClick = (e) => {
    e.stopPropagation();
    if (state) {
      inputRef.current.click();
    }
  };

  useEffect(() => {
    if (showImageList) {
      const fetchData = async () => {
        try {
          const res = await fetch(`/api/admin/files?page=${currentPage}&pageSize=${limit}&type=image`, { method: 'GET', credentials: 'include' });
          const data = await res.json();
          setUploadedImages(data.files || []);
          setTotal(data.total);
        } catch (error) {
          message.error('获取图片列表失败');
        }
      };
      fetchData();
    }
  }, [currentPage, showImageList, limit]);

  const fetchUploadedImages = (e) => {
    e.stopPropagation();
    setCurrentPage(1);
    setShowImageList(true);
  };

  const selectImage = (url) => {
    setImageUrl(url);
    handleChange(url);
    setShowImageList(false);
  };

  return (
    <div className="flex flex-col gap-0.5 my-4 ">
      {label && <label className="form-label text-sm text-gray-600 mb-2">{label}：</label>}
      <div onClick={fetchUploadedImages} className={`w-fit cursor-${state ? 'pointer' : 'default'} border border-dashed border-gray-0 rounded-xs bg-gray-50 hover:bg-gray-100 cursor-pointer ${state ? 'border-gray-400' : 'border-[#ffffff00]'} relative`} >
        {imageUrl ? (
          <Image src={imageUrl} alt={label} width={720} height={720} priority={true} className={`object-contain h-[120px] w-[120px] ${className ? className : ''}`} />
        ) : (
          <div className="flex flex-col items-center justify-center text-black h-[120px] w-[120px]"><Plus size={32} className="text-gray-400" /> <span className="text-xs text-gray-400 mt-2">添加图片</span></div>
        )}
        {state && (<button onClick={handleImageClick} className="absolute bottom-0 right-0 bg-[var(--theme-color)] text-white rounded-none overflow-hidden text-xs cursor-pointer w-6 h-6 p-0.5 shadow" ><ImageUp className='w-full h-full'/></button>)}
      </div>
      <Popup isOpen={showImageList} onClose={() => setShowImageList(false)}>
        <div className="grid grid-cols-2 md:grid-cols-8 gap-6">
          {uploadedImages.length > 0 ?
            uploadedImages.map(({url}) => (<div key={url} onClick={() => selectImage(url)} className="cursor-pointer border border-gray-300 rounded-xs bg-white"> <Image width={720} height={720} src={url} alt="uploaded" className="w-full aspect-square object-contain rounded-none" /> </div>))
            : <> {Array.from({ length: limit }).map((_, i) => (<div key={i} className="skeleton w-full aspect-square"></div>))} </>
          }
        </div>
        <Pagination page={currentPage} total={total} limit={limit} leftDisabled={ currentPage === 1} rightDisabled={currentPage === Math.ceil(total / limit)} leftOnClick={()=> setCurrentPage(p => Math.max(1, p - 1))} rightOnClick={() => setCurrentPage(p => Math.min(Math.ceil(total / limit), p + 1))} />
      </Popup>
      <input ref={inputRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={handleImageChange} />
    </div>
  );
}